package com.blue.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blue.entity.Line;
import com.blue.entity.LineStation;
import com.blue.entity.Station;
import com.blue.mapper.LineMapper;
import com.blue.mapper.LineStationMapper;
import com.blue.mapper.StationMapper;
import com.blue.service.LineStationService;
import com.blue.service.StationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blue.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author blue
 * @since 2024-11-25
 */
@Service
public class StationServiceImpl extends ServiceImpl<StationMapper, Station> implements StationService {
    @Autowired
    LineMapper lineMapper;
    @Autowired
    StationMapper stationMapper;
    @Autowired
    LineStationMapper lineStationMapper;
    @Autowired
    RedisUtils redisUtils;

    @Override
    public Station findStationById(int id) {
        /*s{id}*/
        String tem_id = "s"+String.valueOf(id);
        Station station ;
        if(redisUtils.hasKey(tem_id)){
            station = (Station) redisUtils.get(tem_id);
        }else{
            station =  stationMapper.selectById(id);
           redisUtils.set(tem_id,station);

        }
        redisUtils.incrHotStation(id);
        return station;
    }

    @Override
    public List<Line> findLines(int id) {
        List<Line> list = null;
        String tem_id = "s"+String.valueOf(id)+"lines";

        if(!redisUtils.hasKey(tem_id)){
            QueryWrapper<LineStation> lineStationQueryWrapper = new QueryWrapper<>();
            QueryWrapper<Line> lineQueryWrapper = new QueryWrapper<>();

            lineStationQueryWrapper.eq("station_id", id);
            List<LineStation> lineStations = lineStationMapper.selectList(lineStationQueryWrapper);

            if (!lineStations.isEmpty()) {
                lineQueryWrapper.in("line_id", lineStations.stream().map(LineStation::getLineId).collect(Collectors.toList()));
                // 取出符合条件的line
                list = lineMapper.selectList(lineQueryWrapper);
            } else {
                // 如果没有符合条件的lineStation，返回空列表
                list =  Collections.emptyList();
            }
            redisUtils.set(tem_id,list);
        }else {
            list = (List<Line>) redisUtils.get(tem_id);
        }
        return list;
    }


}
